import { Inject, Controller, Get, Query, Post, Body, App, All } from "@midwayjs/core";
import { Context } from "@midwayjs/koa";
import { HttpService } from "@midwayjs/axios";
// const  {exec}  =require( 'child_process')
import { Application } from "../interface.js";
import { app_fun_dto } from "../models/app_fun.dto.js";
import { failres, okres } from "../config/resUtil.js";
import { UserService } from "../service/user.service.js";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { tb_apisechema_enity } from "../entity/apischemas.entity.js";
import { map as lodashmap } from "lodash-es";
import { BaseDto } from "../models/Base.dto.js";
import { getSkip, getSkipPlus } from "../utils/pageUtil.js";
import { tb_apigroup_entity } from "../entity/tb_apigroup.entity.js";
import { tb_apiitem_enity } from "../entity/tb_apiitem.entity.js";
import { tb_apiitem_dto } from "../models/tb_apiitem.dto.js";
import { lodashEmpty } from "../utils/lodashUtil.js";

const routermap = {
  "个人": "http://127.0.0.1:7001" + "/api/user/apis",
  "生产代码": "http://127.0.0.1:7001" + "/api/gerenrate/apis"

};
type apidosurl = {
  apidosurl: string
  projectCode: string
}

@Controller("/apis/swagger1")
export class _Controller {
  @Inject()
  ctx: Context;
  @App("koa")
  app: Application;

  @Inject()
  userService: UserService;

  @Inject()
  httpService: HttpService;


  @InjectEntityModel(tb_apisechema_enity, "default")
  tb_apisechema_model: Repository<tb_apisechema_enity>;

  @InjectEntityModel(tb_apigroup_entity, "default")
  tb_apigroup_model: Repository<tb_apigroup_entity>;
  @InjectEntityModel(tb_apiitem_enity, "default")
  tb_apiitem_model: Repository<tb_apiitem_enity>;

  @Post("/getshemas")
  async getshemas(@Body() body: tb_apisechema_enity & BaseDto&{name2:string}) {
    var query = this.tb_apisechema_model
      .createQueryBuilder("tb_apisechema").select();
    if (body?.name2) {
      query.where(`name = :name`,{name:body?.name2});
    }else{
      if (body?.name) {
        query.where(`name like '%${body.name}%'`);
      }

    }


    var result = await query.skip(getSkip(body)).take(body.pageSize).getManyAndCount();
    return okres(result?.[0], { total: result?.[1] });
  }


  @Get("/getshemasbyname")
  async getshemasbyname(@Query('name')name:string ) {
  if(!name){
  return failres('没有参数 name')
  }
    var query = this.tb_apisechema_model
      .createQueryBuilder("tb_apisechema").select();
    if (name) {
      query.where(`name = :name`,{name});
    }
    var result = await query.getOne()
    return okres(result);
  }


  @Post("/getapibyurl")
  async getapiitem(@Body() body: tb_apiitem_dto & BaseDto) {
    var query = this.tb_apiitem_model
      .createQueryBuilder("tb_apiitem").select();
    if (body?.name) {
      query = query.where(`name like '%${body.name}%'`);
    }
    if (body?.tagName) {
      query = query.where(`tagname like '%${body.tagName}%'`);
    }
    if (body?.url) {
      query = query.andWhere(`url like '%${body.url}%'`);
    }
    if (body?.projectCode) {
      query = query.andWhere(`project_code = :project_code`, { project_code: body?.projectCode });
    }


    var result3 = await query.skip(getSkip(body)).take(body.pageSize).getManyAndCount();
    var datalist = (result3?.[0] || []) as unknown as tb_apiitem_dto[];
    //获取tagInfo
    for (var i = 0; i < datalist.length; i++) {
      if (datalist?.[i]) {
        datalist[i].tagObj = await this.tb_apigroup_model.findOne({ where: { id: datalist?.[i]?.tagid } });
      }
    }


    return okres(datalist, { total: result3?.[1] });


  }

  @Post("/getapigroup")
  async getapigroup(@Body() body: tb_apigroup_entity & BaseDto) {
    var query = this.tb_apigroup_model
      .createQueryBuilder("tb_apigroup").select();
    if (body?.name) {
      query = query.where(`name like '%${body.name}%'`);
    }
    if (body?.projectCode) {
      query = query.andWhere(`project_code = :project_code`, { project_code: body?.projectCode });
    }


    var result3 = await query.skip(getSkip(body)).take(body.pageSize).getManyAndCount();
    var datalist = (result3?.[0] || []) as unknown as tb_apiitem_dto[];


    // region  获取分组的具体api
    for (let i = 0; i <datalist.length; i++) {
      if(datalist[i].id){
        var detailsList=await this.tb_apiitem_model.find({where:{tagid:datalist[i].id}})
        datalist[i].detailsList=detailsList;
      }

    }
    // endregion

    return okres(datalist, { total: result3?.[1] });


  }

  @Post("/importswaggerui")
  async importswaggerui(@Body() body: apidosurl) {
    var apidosurl = body.apidosurl;
    var projectCode = body?.projectCode;
    if (!apidosurl) {
      return failres("没有数据 apidosurl");
    }
    if (!projectCode) {
      return failres("没有数据 projectCode");
    }
    var result = await this.httpService.get(apidosurl);
    console.log(" apidosurl result :", result);
    var _data = result?.data;
    //处理 schemas
    var schemas = _data?.components?.schemas;
    lodashmap(schemas, async (schema, key) => {
      var exitone = await this.tb_apisechema_model.findOne({
        where: {
          name: key,
          projectCode
        }
      });
      var result2 = undefined;
      if (exitone?.id) {
        var _params = new tb_apisechema_enity({
          name: key,
          projectCode,
          jsoncontent: JSON.stringify(schema?.properties)
        });
        result2 = await this.tb_apisechema_model.update(exitone?.id, _params);
        console.log("insert result2 :", result2);
      } else {
        var _params = new tb_apisechema_enity({
          name: key,
          projectCode,
          jsoncontent: JSON.stringify(schema?.properties)
        });
        result2 = await this.tb_apisechema_model.save(_params);
        console.log("insert result2 :", result2);
      }


    });

    //处理 tags apigroup
    var tags = _data?.tags;
    lodashmap(tags, async (tag) => {
      var exitone = await this.tb_apigroup_model.findOne({ where: { name: tag.name, projectCode: body?.projectCode } });
      if (/**update */exitone?.id) {
        await this.tb_apigroup_model.update(exitone?.id, { name: tag?.name, desc: tag?.description });
      } else {
        await this.tb_apigroup_model.insert({
          name: tag?.name,
          desc: tag?.description,
          projectCode: body?.projectCode
        });
      }
    });

    //处理paths  tb_apiitem
    var pathsmap = _data?.paths;
    var pathList = lodashmap(pathsmap, (pathMap, url) => {
      return {
        ...pathMap,
        url
      };
    });
    for (let i = 0; i < pathList.length; i++) {
      var pathMap = pathList[i];
      var _method = Object.keys(pathMap)?.[0];
      var _pathObj = pathMap?.[_method];
      var url = pathList[i].url;

      var tag_params = _pathObj?.tags?.[0];
      var tag = await this.tb_apigroup_model.findOne({ where: { name: tag_params, projectCode: body?.projectCode } });
      console.log("=>(swagger1.controller.ts:201) tag", _pathObj?.tags,tag_params,tag?.id);



      var exitapi = await this.tb_apiitem_model.findOne({
        where: { method: _method, url: url, projectCode: body?.projectCode }
      });
      // 修改
      if (exitapi?.id) {
      if(_pathObj?.parameters){
      }
        await this.tb_apiitem_model.update(exitapi?.id, new tb_apiitem_enity({
          name: _pathObj?.summary,
          url, method: _method,
          request: JSON.stringify(_pathObj?.requestBody),
          parameters: JSON.stringify(_pathObj?.parameters),
          response: JSON.stringify(_pathObj?.responses),
          projectCode: body?.projectCode,
          tagid: tag?.id,
          tagname: tag?.name
        }));

      } else {
        await this.tb_apiitem_model.save(new tb_apiitem_enity({
          name: _pathObj?.summary,
          url, method: _method,
          request: JSON.stringify(_pathObj?.requestBody),
          parameters: JSON.stringify(_pathObj?.parameters),
          response: JSON.stringify(_pathObj?.responses),
          projectCode: body?.projectCode,
          tagid: tag?.id,
          tagname: tag?.name
        }));
      }
    }


    return okres("");

  }

}
